from os import error
from flask import Blueprint,render_template, request,session,redirect
from config import conn,cur,mutex ,r as redis
import datetime

Communication = Blueprint('Communication',__name__)
 
@Communication.route('/',methods=["GET", "POST"])
def index():
    id = session.get('id') 
    name = session.get('name')

    sqlstr='select d.id, d.name, d.email, d.cellphone from personal_info p join doctor_info d on p.doctor_id=d.id where p.id = \'' + str(id)+'\''
    print(sqlstr)
    cur.execute(sqlstr)
    result = cur.fetchall()

    sqlstr='select id, email, cellphone from personal_info where id = \'' + str(id)+'\''
    print(sqlstr)
    cur.execute(sqlstr)
    docinfo = cur.fetchall()

    sqlstr="select [text], send_by from [message] m join personal_info p on m.patient_id=p.id and m.doctor_id=p.doctor_id where patient_id='"+str(id)+"' order by [time]"
    print(sqlstr)
    cur.execute(sqlstr)
    chatinfo = cur.fetchall()
    
    return render_template('/communication/index.html',id =id,name=name,data=result,docinfo=docinfo,chatinfo=chatinfo)

@Communication.route('/modifycom',methods=["GET", "POST"])
def modifycom():
    id = request.form.get("id")
    email = request.form.get("email")
    tel = request.form.get("tel")
    sqlstr='UPDATE personal_info SET email=\''+email+'\', cellphone=\''+ tel +'\' WHERE id=\''+ id+'\''
    print(sqlstr)
    cur.execute(sqlstr)
    conn.commit()

    return {"message":"success!"}

@Communication.route('/sendmss',methods=["GET", "POST"])
def sendmss():
    id = session.get('id') 
    name = session.get('name')
    
    mes = request.form.get("mes")

    sqlstr = "select doctor_id from personal_info where id='"+str(id)+"'"
    cur.execute(sqlstr)
    did = cur.fetchall()[0][0]

    sqlstr= "insert into [message] (doctor_id, patient_id, [text], send_by) VALUES ('"+str(did)+"', '"+str(id)+"', '"+mes+"', 'p');"
    print(sqlstr)
    cur.execute(sqlstr)
    conn.commit()
    
    return {"message":"success!"}

@Communication.before_request
def before():
    if session.get('id') is None or session.get('role') != 'patient':
        return redirect('/Login/',code=301)
    else:
        pass